from django.contrib.auth import get_user_model
from rest_framework import viewsets, permissions
from rest_framework.response import Response
from rest_framework.decorators import action
from rest_framework.exceptions import ErrorDetail, ValidationError

from user.permission import IsAdminUser, IsReseacherUser, IsStudentUser
from .models import Question
from .serializers import QuestionChangeSerializer, QuestionGetSerializer

User = get_user_model()


class QuestionViewSet(viewsets.ModelViewSet):
    queryset = Question.objects.all()
    serializer_class = QuestionChangeSerializer
    # filter_backends = [DjangoFilterBackend, filters.OrderingFilter]
    filterset_fields = {
        'id': ['exact'],
        'answer': ['isnull'],
        'asked_by': ['exact'],
        'rejected_by': ['exact', 'isnull'],
        'audited_by': ['exact', 'isnull'],
        'answered_by': ['exact'],
    }

    def get_permissions(self):
        if self.action == 'list' or self.action == 'retrieve':
            permission_classes = [permissions.IsAuthenticated]
        elif self.action == 'create' or self.action == 'destroy':
            permission_classes = [IsStudentUser]
        elif self.action == 'audit':
            permission_classes = [IsAdminUser]
        elif self.action == 'answer':
            permission_classes = [IsReseacherUser]
        else:
            permission_classes = []
        return [permission() for permission in permission_classes]

    def get_serializer_class(self):
        if self.action in ['list', 'retrieve']:
            return QuestionGetSerializer
        else:
            return QuestionChangeSerializer

    def create(self, request, *args, **kwargs):
        request.data['asked_by'] = request.user.id
        return super().create(request, *args, **kwargs)

    @action(detail=True, methods=['patch'])
    def edit(self, request, pk):
        request.data['rejected_by'] = None
        return self.partial_update(request, pk)

    @action(detail=True, methods=['patch'])
    def audit(self, request, pk):
        request.data['audited_by'] = request.user.id
        return self.partial_update(request, pk)

    @action(detail=True, methods=['patch'])
    def reject(self, request, pk):
        request.data['rejected_by'] = request.user.id
        return self.partial_update(request, pk)

    @action(detail=True, methods=['patch'])
    def answer(self, request, pk):
        request.data['answered_by'] = request.user.id
        answer = request.data.get('answer')
        if not answer:
            raise ValidationError(ErrorDetail('answer field is required', code='required'))
        return self.partial_update(request, pk)
